//
//  FQFillInfoViewController.swift
//  SwiftProject
//
//  Created by 董駸 on 2022/8/22.
//

import UIKit

enum FillType {
    case kinsfolk
    case baseInfo
}

class FQFillInfoViewController: BaseViewController, UITableViewDelegate, UITableViewDataSource {
    var nameAes : String = ""
    var idCardAes : String = ""
    
    var fillType : FillType = .kinsfolk
    var regionData : [FQRegionDataModel] = []
    let mainTable = UITableView(frame: .zero, style: .grouped)
    var sectionArray : [String] = []
    var modelArray : [[FQFillInfoModel]] = []
    
    var expandModelArray1 : [FQFillInfoModel] = []
    var expandModelArray2 : [FQFillInfoModel] = []
    var expandModelArray3 : [FQFillInfoModel] = []

    var expandModel : FQFillInfoModel!
    let bottomView = FQAuthBottonView()

    var resultModel = FQFillResultModel()
    
    convenience init(_ fillType : FillType) {
        self.init(nibName: nil, bundle: nil)
        self.fillType = fillType
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationBarType = .light
    }
    
    override func initSubviews() {
        super.initSubviews()
        let userModel = BaseUserModel.unarchiver()!
        let configModel = YHBaseConfiguration.shared.configModel!
        
        if !nameAes.isEmpty && !idCardAes.isEmpty {
            resultModel.nameAes = nameAes
            resultModel.idNumberAes = idCardAes
        }

        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(90)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
        
        bottomView.toggleBlock = { [unowned self] isSelected in
            self.bottomView.completionBtn.isEnabled = self.doCheck()
        }
        
        bottomView.buttonBlock = { [unowned self] in
            switch self.fillType {
            case .kinsfolk:
                let modelList = modelArray.flatMap { model in
                    model.map{ $0 }
                }
                let relationModel1 = FQRelationshipModel()
                let relationModel2 = FQRelationshipModel()

                relationModel1.type = modelList.filter{ $0.title == "亲属关系" }.first!.code + 1
                relationModel2.type = 0
                
                relationModel1.nameAes = WMEncryptTool.manager.aesEncrypt(modelList.filter{ $0.title == "姓名" }.first!.detail)
                relationModel1.phoneAes = WMEncryptTool.manager.aesEncrypt(modelList.filter{ $0.title == "手机号" }.first!.detail)

                relationModel2.nameAes = WMEncryptTool.manager.aesEncrypt(modelList.filter{ $0.title == "姓名" }.last!.detail)
                relationModel2.phoneAes = WMEncryptTool.manager.aesEncrypt(modelList.filter{ $0.title == "手机号" }.last!.detail)
                resultModel.accountMemberRelationship = [relationModel1, relationModel2]
                
                let vc = FQFillInfoViewController(.baseInfo)
                vc.resultModel = resultModel
                self.navigationController?.qmui_pushViewController(vc, animated: true)
            case .baseInfo:
                let modelList = modelArray.flatMap { model in
                    model.map{ $0 }
                }
                
                if let dataModel = modelList.filter({ $0.title == "您的学历" }).first {
                    self.resultModel.education = dataModel.code + 1
                }
                
                if let dataModel = modelList.filter({ $0.title == "职业类别" }).first {
                    self.resultModel.occupationType = dataModel.code + 1
                }
                if let dataModel = modelList.filter({ $0.title == "所属行业" }).first {
                    self.resultModel.trade = dataModel.code + 1
                }
                if let dataModel = modelList.filter({ $0.title == "公司名称" }).first {
                    self.resultModel.companyName = dataModel.detail
                }
                if let dataModel = modelList.filter({ $0.title == "公司地址" }).first {
                    self.resultModel.companyAddress = dataModel.detail
                }
                if let dataModel = modelList.filter({ $0.title == "详细地址" }).first {
                    self.resultModel.companyFullAddress = dataModel.detail
                }
                if let dataModel = modelList.filter({ $0.title == "公司电话" }).first {
                    self.resultModel.companyTelephone = dataModel.detail
                }
                if let dataModel = modelList.filter({ $0.title == "公司性质" }).first {
                    self.resultModel.companyProperties = dataModel.code + 1
                }
                
                if let dataModel = modelList.filter({ $0.title == "所在城市" }).first {
                    if dataModel.model.text.contains("市辖区") {
                        self.resultModel.city = dataModel.model.value[0..<2]
                        self.resultModel.realCity = dataModel.model.value[0..<3]
                    } else {
                        self.resultModel.city = dataModel.model.text
                        self.resultModel.realCity = dataModel.model.value
                    }
                }
                if let dataModel = modelList.filter({ $0.title == "芝麻分" }).first {
                    self.resultModel.zhiMa = dataModel.code + 1
                }
                if let dataModel = modelList.filter({ $0.title == "个人资产" }).first {
                    self.resultModel.accumulationFound = dataModel.detail.contains("有公积金")
                    self.resultModel.house = dataModel.detail.contains("有房")
                    self.resultModel.car = dataModel.detail.contains("有车")
                    self.resultModel.creditCardLimit = dataModel.detail.contains("有信用卡")
                    self.resultModel.jdBaitiao = dataModel.detail.contains("有京东白条")
                    self.resultModel.socialSecurity = dataModel.detail.contains("有社保")
                    self.resultModel.myHuabei = dataModel.detail.contains("有花呗")
                    self.resultModel.profession = dataModel.detail.contains("企业主")
                }
                
                if let dataModel = modelList.filter({ $0.title == "借款额度" }).first {
                    self.resultModel.loanLimit = dataModel.code + 1
                }
                if let dataModel = modelList.filter({ $0.title == "借款用途" }).first {
                    self.resultModel.loanUse = dataModel.code + 1
                }
                if let dataModel = modelList.filter({ $0.title == "负债情况" }).first {
                    self.resultModel.debtSituation = dataModel.code + 1
                }
                if let dataModel = modelList.filter({ $0.title == "月收入" }).first {
                    self.resultModel.monthlyIncome = dataModel.code + 1
                }

                NetworkManager.manager.request(targetType: .accountMember(model: self.resultModel), responseModelType: NetworkDefualtModel.self) { responseModel in
                    if responseModel.code != .successCode {
                        QMUITips.showError(responseModel.msg)
                        return
                    }
                    self.navigationController?.qmui_pushViewController(FQAuditViewController(), animated: true)
                }
            }
        }
        
        var titleArray : [[[String : Any]]] = []
        switch fillType {
        case .kinsfolk:
            sectionArray = ["您的直属联系人", "普通联系人"]
            titleArray = [[["title" : "亲属关系", "placeholder" : "请选择", "type" : 3],
                           ["title" : "姓名", "placeholder" : "请填写真实姓名", "type" : 0],
                           ["title" : "手机号", "placeholder" : "请输入手机号", "type" : 1]],
                          [["title" : "姓名", "placeholder" : "请填写真实姓名", "type" : 0],
                           ["title" : "手机号", "placeholder" : "请输入手机号", "type" : 1]]
            ]
            bottomView.completionBtn.setTitle("填写个人资料", for: .normal)
        case .baseInfo:
            bottomView.completionBtn.setTitle("前往审核", for: .normal)

            sectionArray = []
            titleArray = []
            
            if configModel.education && !userModel.isAccomplishEducation {
                sectionArray.append("")
                titleArray.append([["title" : "您的学历", "placeholder" : "请选择", "type" : 4]])
            }
            
            if configModel.workInformation && !userModel.isAccomplishWorkInfo {
                sectionArray.append("工作信息")
                titleArray.append([["title" : "职业类别", "placeholder" : "请选择", "type" : 6]])
            }
            
            if configModel.loanAssistance && !userModel.completeInformation {
                sectionArray.append("")
                titleArray.append([["title" : "所在城市", "placeholder" : "请选择", "type" : 14]])
                sectionArray.append("芝麻分")
                titleArray.append([["title" : "芝麻分", "placeholder" : "", "type" : 15]])
                sectionArray.append("个人资产（多选）")
                titleArray.append([["title" : "个人资产", "placeholder" : "", "type" : 16]])
                
                NetworkManager.manager.request(targetType: .city, responseModelType: NetworkBaseListModel<FQRegionDataModel>.self) { responseModel in
                    if responseModel.code != .successCode {
        //                    QMUITips.showError(responseModel.msg)
                        return
                    }
                    self.regionData = responseModel.data!
                    
                    NetworkManager.manager.request(targetType: .ipPositioning, responseModelType: NetworkBaseModel<FQLocationModel>.self) { responseModel in
                        if responseModel.code != .successCode {
                            QMUITips.showError(responseModel.msg)
                            return
                        }
                        var region : FQRegionDataModel!
                        for (_, item) in self.regionData.enumerated() {
                            for (_, item2) in item.children.enumerated() {
                                if responseModel.data!.adcode == item2.regionCode {
                                    region = item2
                                    break
                                }
                            }
                        }
                        for (index, item) in self.modelArray.enumerated() {
                            for (index2, item2) in item.enumerated() {
                                if item2.title == "所在城市" {
                                    item2.detail = responseModel.data!.city
                                    item2.model = region
                                    self.mainTable.reloadRows(at: [IndexPath(row: index2, section: index)], with: .none)
                                    break
                                }
                            }
                        }
                    }
                }
            }
            
            if configModel.loanInformation && !userModel.completeInformation {
                sectionArray.append("借款信息")
                titleArray.append([["title" : "借款额度", "placeholder" : "请选择", "type" : 19],
                                   ["title" : "借款用途", "placeholder" : "请选择", "type" : 10],
                                   ["title" : "负债情况", "placeholder" : "请选择", "type" : 11],
                                   ["title" : "月收入", "placeholder" : "请选择", "type" : 12]])
            }
            
            let expandArray1 : [[String : Any]] = [["title" : "所属行业", "placeholder" : "请选择", "type" : 7],
                                                  ["title" : "公司名称", "placeholder" : "如无所属公司，请填写个体", "type" : 0],
                                                  ["title" : "公司性质", "placeholder" : "请选择", "type" : 8],
                                                  ["title" : "公司地址", "placeholder" : "请选择", "type" : 5],
                                                  ["title" : "详细地址", "placeholder" : "请填写详细的街道号", "type" : 0],
                                                  ["title" : "公司电话", "placeholder" : "如无，可不填", "type" : 9]]
            expandModelArray1 = expandArray1.map({ dict in
                FQFillInfoModel.deserialize(from: dict)!
            })
        }
        modelArray = titleArray.map({ sectionArray in
            sectionArray.map ({ dict in
                FQFillInfoModel.deserialize(from: dict)!
            })
        })
        
        safeAreaBottomView.backgroundColor = .white
        
        mainTable.dataSource = self
        mainTable.delegate = self
        mainTable.backgroundColor = .qmui_color(withHexString: "f5f5f5")
        mainTable.register(FQFillInfoTableViewCell.self, forCellReuseIdentifier: "cell")
        mainTable.register(FQFillInfoSectionView.self, forHeaderFooterViewReuseIdentifier: "header")
        mainTable.register(FQSesameTableViewCell.self, forCellReuseIdentifier: "sesame")
        mainTable.register(FQPropertyTableViewCell.self, forCellReuseIdentifier: "property")
        mainTable.tableHeaderView = FQFillInfoHeaderView(fillType)
        view.addSubview(mainTable)
        
        mainTable.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(bottomView.snp.top)
            make.top.equalTo(NavigationContentTop)
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        modelArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        modelArray[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = modelArray[indexPath.section][indexPath.row]

        if model.type == .sesame {
            let cell = tableView.dequeueReusableCell(withIdentifier: "sesame") as! FQSesameTableViewCell
            cell.model = model
            return cell
        } else if model.type == .property {
            let cell = tableView.dequeueReusableCell(withIdentifier: "property") as! FQPropertyTableViewCell
            cell.model = model
            return cell
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! FQFillInfoTableViewCell
        cell.model = model
        cell.fillBlock = { [unowned self] in
            if model.type == .jobType && model.detail != "无业" {
                let index = sectionArray.firstIndex(of: "工作信息")!
                var modelArr = modelArray[index]
                if modelArr.count == 1 {
                    modelArr += expandModelArray1
                    modelArray[index] = modelArr
                    tableView.reloadData()
                }
            } else if model.type == .jobType && model.detail == "无业" {
                let index = sectionArray.firstIndex(of: "工作信息")!
                var modelArr = modelArray[index]
                if modelArr.count != 1 {
                    modelArr.removeSubrange(Range(NSRange(location: 1, length: modelArr.count - 1))!)
                    modelArray[index] = modelArr
                    tableView.reloadData()
                }
            }
        }
        cell.checkBlock = { [unowned self] in
            self.bottomView.completionBtn.isEnabled = self.doCheck()
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if modelArray[indexPath.section][indexPath.row].type.rawValue == 15 {
            return 112
        } else if modelArray[indexPath.section][indexPath.row].type.rawValue == 16 {
            return 185
        }
        return 50
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if sectionArray[section].isEmpty && section != 0 {
            return 24
        } else if section == 0 {
            return .leastNonzeroMagnitude
        }
        return 53
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        .leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "header") as! FQFillInfoSectionView
        header.titleLb.text = sectionArray[section]
        return header
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        nil
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if let cell = tableView.cellForRow(at: indexPath) as? FQFillInfoTableViewCell {
            let model = modelArray[indexPath.section][indexPath.row]
            if model.type == .city {
                cell.doAction(regionData)
            } else {
                cell.doAction()
            }
        }
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        cell.separatorInset = .zero
    }
    
    func doCheck() -> Bool {
        if !bottomView.selectBtn.isSelected {
            return false
        }
        if fillType == .kinsfolk {
            for item in modelArray {
                for item1 in item {
                    if item1.detail.isEmpty {
                        return false
                    }
                }
            }
        } else {
            for item in modelArray {
                for item1 in item {
                    if item1.detail.isEmpty && item1.title != "公司电话" {
                        return false
                    }
                }
            }
        }
        return true
    }
    
    override func shouldPopViewController(byBackButtonOrPopGesture byPopGesture: Bool) -> Bool {
        if fillType == .baseInfo {
            let v = FQFillInfoTipView()
            modalViewControllerForAddSubview.contentView = v
            modalViewControllerForAddSubview.showWith(animated: true)
            
            v.buttonBlock = { [unowned self] tag in
                modalViewControllerForAddSubview.hideWith(animated: true)
                if tag == 2 {
                    navigationController?.qmui_popViewController(animated: true)
                }
            }
            return false
        }
        return true
    }
    
    override func setupNavigationItems() {
        super.setupNavigationItems()
        switch fillType {
        case .baseInfo:
            title = "基本信息"
        case .kinsfolk:
            title = "亲属关系填写"
        }
    }
}
